package sqlanalysisgui.editor;

import java.awt.Color;
import java.awt.GradientPaint;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.experimental.chart.swt.ChartComposite;

import sqlanalysisgui.view.model.FileAnalysisInfo;
import sqlanalysisgui.view.model.ProjectInfo;

import com.cho.core.db.dao.TableDao;
import com.cho.core.util.StringUtils;

public class DashboardGraph extends EditorPart {
	public static final String ID = "sqlanalysisgui.editor.DashboardGraph"; //$NON-NLS-1$
	private Logger logger = Logger.getLogger(this.getClass());
	private Text text;
	private Text text_1;
	private Table table;
	private Table table_1;
	private ProjectInfo projectInfo;

	private DashboardTableInput input;

	public DashboardGraph() {
	}

	/**
	 * Create contents of the editor part.
	 * 
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		/* Composite container = new Composite(parent, SWT.NONE); */
		parent.setLayout(new FillLayout(SWT.HORIZONTAL));
		ChartComposite chartComposite_1 = new ChartComposite(parent, SWT.NONE,
				createChartForCrudRatio(createDatasetForCrudRatio()), true);

		ChartComposite chartComposite = new ChartComposite(parent, SWT.NONE,
				createChartForTableRatio(createDatasetForTableRatio()), true);
	}

	/**
	 * Creates the Dataset for the Pie chart
	 */

	private PieDataset createDatasetForCrudRatio() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		List<FileAnalysisInfo> fileAnalysisInfos = TableDao.selectProjectFileAnalysisInfo(projectInfo.getProjectName());
		
		if(fileAnalysisInfos.size() > 0){
			FileAnalysisInfo fileAnalysisInfo = fileAnalysisInfos.get(0);
			
			dataset.setValue("INSERT", new Double(StringUtils.nvl(fileAnalysisInfo.getcTypeRatio(), "0.0")));
			dataset.setValue("SELECT", new Double(StringUtils.nvl(fileAnalysisInfo.getrTypeRatio(), "0.0")));
			dataset.setValue("UPDATE", new Double(StringUtils.nvl(fileAnalysisInfo.getuTypeRatio(), "0.0")));
			dataset.setValue("DELETE", new Double(StringUtils.nvl(fileAnalysisInfo.getdTypeRatio(), "0.0")));
		}

		return dataset;
	}

	/**
	 * Creates the Chart based on a dataset
	 */

	private JFreeChart createChartForCrudRatio(PieDataset dataset) {

		JFreeChart chart = ChartFactory.createPieChart("CRUD별 빈도", // chart
				// title
				dataset, // data
				true, // include legend
				true, false);

		PiePlot plot = (PiePlot) chart.getPlot();
		plot.setSectionOutlinesVisible(false);
		// plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
		plot.setNoDataMessage("No data available");
		plot.setCircular(false);
		plot.setLabelGap(0.02);
		return chart;
	}
	/**
	 * Creates the Dataset for the Pie chart
	 */
	
	private CategoryDataset createDatasetForTableRatio() {
		DefaultCategoryDataset  dataset = new DefaultCategoryDataset ();
		List<FileAnalysisInfo> fileAnalysisInfos = TableDao.selectProjectTableUseTopTenAnalysisList(projectInfo.getProjectName());
		
		for (int i = 0; i < fileAnalysisInfos.size() - 1; i++) {
			FileAnalysisInfo fileAnalysisInfo = fileAnalysisInfos.get(i);
			dataset.setValue(new Double(StringUtils.nvl(fileAnalysisInfo.getTotalCount(), "0.0")), fileAnalysisInfo.getTableName(), "테이블");
			
			//dataset.addValue(1.0, series1, category1);
		}
		
		return dataset;
	}
	
	/**
	 * Creates the Chart based on a dataset
	 */
	
	private JFreeChart createChartForTableRatio(CategoryDataset  dataset) {
		
		JFreeChart chart = ChartFactory.createBarChart(
			     "테이블 사용 횟수 상위 10개",         // chart title
		            "테이블 종류",               // domain axis label
		            "횟수",                  // range axis label
		            dataset,                  // data
		            PlotOrientation.VERTICAL, // orientation
		            true,                     // include legend
		            true,                     // tooltips?
		            false                     // URLs?
		        );
		
		 // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

        // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

        // get a reference to the plot for further customisation...
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.white);

        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        // disable bar outlines...
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);
        
        // set up gradient paints for series...
        GradientPaint gp0 = new GradientPaint(
            0.0f, 0.0f, Color.blue, 
            0.0f, 0.0f, new Color(0, 0, 64)
        );
        GradientPaint gp1 = new GradientPaint(
            0.0f, 0.0f, Color.green, 
            0.0f, 0.0f, new Color(0, 64, 0)
        );
        GradientPaint gp2 = new GradientPaint(
            0.0f, 0.0f, Color.red, 
            0.0f, 0.0f, new Color(64, 0, 0)
        );
        renderer.setSeriesPaint(0, gp0);
        renderer.setSeriesPaint(1, gp1);
        renderer.setSeriesPaint(2, gp2);

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(
            CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
        );
        // OPTIONAL CUSTOMISATION COMPLETED.
		
		return chart;
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// Do the Save operation
	}

	@Override
	public void doSaveAs() {
		// Do the Save As operation
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		// Initialize the editor part

		logger.debug("site: " + site);
		logger.debug("site.getId: " + site.getId());
		logger.debug("input: " + input);

		if (!(input instanceof DashboardTableInput)) {
			throw new RuntimeException("Wrong input");
		}

		this.input = (DashboardTableInput) input;
		setSite(site);
		setInput(input);
		projectInfo = ((DashboardTableInput)input).getProjectInfo(); 
		// proejctInfo =
		// MyModel.getInstance().getPersonById(this.input.getId());
		// setPartName("Person ID: " + proejctInfo.getId());
		setPartName("DASH BOARD");

	}

	@Override
	public boolean isDirty() {
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

}
